package com.dmcb.trade.business.crawlers.article;

import com.dmcb.common.business.utils.DateUtil;
import com.dmcb.trade.business.constants.CrawlConstant;
import com.dmcb.trade.business.entities.Article;
import org.jsoup.nodes.Document;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * created by 王勇 on 2018/9/27.
 */
@Service
public class TouZiSheQuParser extends BaseParser {

    /**
     * 网站URL网址
     *
     * @return 链接
     */
    @Override
    protected String url() {
        return CrawlConstant.TOUZISHEQU_URL;
    }

    /**
     * 获取标题选择器
     *
     * @return 标题选择器
     */
    @Override
    protected String titleSelect() {
        return "h1#thread_subject,h1";
    }

    /**
     * 获取日期选择器
     *
     * @return 发布日期选择器
     */
    @Override
    protected String dateSelect() {
        return "span.time";
    }

    /**
     * 获取正文内容选择器
     *
     * @return 正文内容选择器
     */
    @Override
    protected String bodySelect() {
        return "div.content-wrap";
    }

    /**
     * 获取封面选择器
     *
     * @return 封面选择器
     */
    @Override
    protected String coverSelect() {
        return "div.content-wrap img[src]";
    }

    /**
     * 获取作者选择器
     *
     * @return 作者选择器
     */
    @Override
    protected String authorNameSelect() {
        return "div.username";
    }


    @Override
    protected void setPostDate(Document doc, Article article) {
        Date time = new Date();

        String data = doc.select(dateSelect()).text();
        if (data != null & data.contains("天")) {
            String[] datas = data.split(" ");
            Date date = new Date();
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(date);
            int num =0;
            if(data.contains("昨天")){
                num =-1;
            }else if(data.contains("前天")||data.contains("两天前")||data.contains("2 天前")){
                num =-2;
            }else if(data.contains("大前天")||data.contains("三天前")||data.contains("3 天前")){
                num =-3;
            }else{
                num =-Integer.parseInt(data.substring(0,data.indexOf("天")).replace(" ","").trim());
            }

            calendar.add(calendar.DATE, num);
            time = calendar.getTime();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd ");
            String dateString = format.format(time);
            if(!data.contains("天前")){
                dateString = dateString+datas[1];
            }

            time = DateUtil.parseDate(dateString);


        } else {
            time = DateUtil.parseDate(data);
        }

        article.setPostTime(time);
    }

    @Override
    protected String platform() {
        return "投资社区";
    }
}
